<template>
  <el-dialog
    v-model="internalVisible"
    :before-close="handleClose"
    class="notice-detail-dialog"
    destroy-on-close
    :title="`通知详情 (任务ID: ${props.taskId})`"
    width="75%"
  >
    <div v-loading="loading" class="notice-detail-content">
      <!-- 检索表单 -->
      <!-- <div class="detail-search">
        <el-form :inline="true" :model="detailQuery">
          <el-form-item label="接收人">
            <el-input v-model="detailQuery.userId" placeholder="请输入接收人" />
          </el-form-item>
          <el-form-item label="发送状态">
            <el-select v-model="detailQuery.notifySendStatus" clearable placeholder="请选择发送状态">
              <el-option v-for="[value, label] in Object.entries(statusDict.notifySendStatus)" :key="value" :label="label" :value="value" />
            </el-select>
          </el-form-item>
          <el-form-item label="接收状态">
            <el-select v-model="detailQuery.notifyReceiveStatus" clearable placeholder="请选择接收状态">
              <el-option
                v-for="[value, label] in Object.entries(statusDict.notifyReceiveStatus)"
                :key="value"
                :label="label"
                :value="value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div> -->

      <!-- 详情表格 -->
      <el-table class="detail-table" :data="list">
        <el-table-column label="接收人" prop="user.name" width="120" />
        <el-table-column label="发送状态" prop="notifySendStatus" width="100">
          <template #default="{ row }">
            {{ statusDict.notifySendStatus[row.notifySendStatus] }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="接收状态" prop="notifyReceiveStatus" width="100">
          <template #default="{ row }">
            {{ statusDict.notifyReceiveStatus[row.notifyReceiveStatus] }}
          </template>
        </el-table-column> -->
        <el-table-column label="通知时间" prop="notifyTime" width="160" />
        <el-table-column label="内容预览" min-width="200" prop="content">
          <template #default="{ row }">
            <div class="content-cell" @click="handleViewContent(row)">
              <el-tooltip :content="getTooltipContent(row.content)" effect="dark" placement="top">
                <div class="truncated-content" v-html="truncateContent(row.content)"></div>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template #default="{ row }">
            <el-button :disabled="row.notifySendStatus != '0'" size="small" type="primary" @click="handleResend(row)">重新发送</el-button>
            <!-- <el-button size="small" type="primary" @click="handleResend(row)">重新发送</el-button> -->
            <!-- <el-button size="small" type="info" @click="handleViewContent(row)">查看完整内容</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-if="total > 0"
        class="pagination-footer"
        :current-page="detailQuery.page"
        :layout="layout"
        :page-size="detailQuery.limit"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />

      <!-- 通知内容查看弹窗 (内部) -->
      <el-dialog
        v-model="showFullContentDialog"
        append-to-body
        class="full-content-dialog"
        destroy-on-close
        title="完整通知内容"
        width="60%"
      >
        <div class="notification-content-full" v-html="selectedContent"></div>
        <template #footer>
          <el-button @click="showFullContentDialog = false">关闭</el-button>
        </template>
      </el-dialog>
    </div>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { onMounted, ref, watch } from 'vue'
import type { NotificationDetail } from '../config'
import { moduleApi, statusDict } from '../config'
import request from '/@/utils/request'

interface Props {
  modelValue: boolean // Controls dialog visibility
  taskId: string | null // Task ID to fetch details for
}

interface RequestResponse<T = any> {
  code: number
  result: T
  message?: string
}

const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
}>()

// Internal visibility state synced with prop
const internalVisible = ref(props.modelValue)
watch(
  () => props.modelValue,
  (newVal) => {
    internalVisible.value = newVal
    if (newVal && props.taskId) {
      detailQuery.value.taskId = props.taskId // Ensure taskId is set for query
      detailQuery.value.page = 1 // Reset to first page when opening
      fetchData()
    } else if (!newVal) {
      // Reset data when dialog closes to avoid showing old data briefly
      list.value = []
      total.value = 0
    }
  }
)

const handleClose = () => {
  emit('update:modelValue', false)
}

// 状态定义
const loading = ref(false)
const list = ref<NotificationDetail[]>([])
const total = ref(0)
const layout = ref('total, sizes, prev, pager, next, jumper')
const showFullContentDialog = ref(false) // For the internal dialog showing full content
const selectedContent = ref('')

// 查询参数
const detailQuery = ref({
  page: 1,
  limit: 10, // Adjusted for dialog view
  taskId: props.taskId || '',
})

// Watch for taskId changes if the dialog is already open
watch(
  () => props.taskId,
  (newTaskId) => {
    if (internalVisible.value && newTaskId) {
      detailQuery.value.taskId = newTaskId
      detailQuery.value.page = 1
      fetchData()
    }
  }
)

// 获取详情数据
const fetchData = async () => {
  const currentTaskIdToFetch = detailQuery.value.taskId
  if (!currentTaskIdToFetch) {
    console.warn('[NoticeDetail] fetchData called without a valid taskId.')
    list.value = [] // Clear list if no taskId
    total.value = 0
    return
  }

  loading.value = true
  try {
    const res = (await request({
      url: `${moduleApi}/show/${currentTaskIdToFetch}`,
      method: 'get',
      params: {
        page: detailQuery.value.page,
        limit: detailQuery.value.limit,
        taskId: currentTaskIdToFetch,
      },
    })) as RequestResponse<{ rows: NotificationDetail[]; count: number }>
    if (res?.code === 0 && res?.result) {
      list.value = res.result.rows
      total.value = res.result.count
    } else {
      list.value = []
      total.value = 0
      ElMessage.error(res?.message || '获取通知详情失败')
    }
  } catch (error: any) {
    list.value = []
    total.value = 0
    console.error('获取通知详情失败:', error)
    ElMessage.error(error.message || error.msg || '获取通知详情失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  if (props.modelValue && props.taskId) {
    if (detailQuery.value.taskId !== props.taskId) {
      detailQuery.value.taskId = props.taskId
    }
    detailQuery.value.page = 1 // Reset page on mount if opening
    fetchData()
  }
})

// 重新发送通知
const handleResend = async (row: NotificationDetail) => {
  if (!row.id) {
    ElMessage.error('缺少必要ID，无法重新发送')
    return
  }
  try {
    // api/notification/taskResend
    // mrr.qssite.cn/api/notification/task/resend/
    // api/notification/taskResend
    const res = (await request({
      url: `api/notification/taskResend`, // Assuming row.id is the specific ID for resending this user's notification
      data: {
        id: row.id,
      },
      method: 'post',
    })) as RequestResponse<null>
    if (res?.code === 0) {
      ElMessage.success('重新发送成功')
      fetchData() // Refresh list
    } else {
      ElMessage.error(res?.message || '重新发送失败')
    }
  } catch (error: any) {
    console.error('重新发送失败:', error)
    ElMessage.error(error.message || error.msg || '重新发送失败')
  }
}

// 查看通知内容 (triggers internal dialog)
const handleViewContent = (row: NotificationDetail) => {
  selectedContent.value = row.content
  showFullContentDialog.value = true
}

const truncateContent = (htmlContent: string, maxLength = 50) => {
  if (!htmlContent) return ''
  const textContent = htmlContent.replaceAll(/<[^>]+>/g, '') // Strip HTML tags
  return textContent.length > maxLength ? `${textContent.substring(0, maxLength)}...` : textContent
}

const getTooltipContent = (htmlContent: string) => {
  if (!htmlContent) return '无内容'
  return htmlContent.replaceAll(/<[^>]+>/g, '')
}

// Removed handleSearch and handleReset functions as their UI is commented out
// and they are no longer used.
// const handleSearch = () => { ... }
// const handleReset = () => { ... }

const handleSizeChange = (val: number) => {
  detailQuery.value.limit = val
  detailQuery.value.page = 1
  fetchData()
}

const handleCurrentChange = (val: number) => {
  detailQuery.value.page = val
  fetchData()
}

// No initial fetchData() call here, it's triggered by prop change
</script>

<style lang="scss" scoped>
.notice-detail-dialog {
  .notice-detail-content {
    min-height: 400px; // Ensure a minimum height for content area
    max-height: calc(80vh - 180px); // Max height considering dialog header/footer
    overflow-y: auto;
  }

  .detail-search {
    padding: 10px;
    margin-bottom: 16px;
    background-color: #f9f9f9;
    border-radius: 4px;
  }

  .detail-table {
    margin-bottom: 16px;
  }

  .content-cell {
    cursor: pointer;
    &:hover {
      color: #409eff;
    }
  }
  .truncated-content {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .pagination-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 15px;
  }
}

.full-content-dialog {
  .notification-content-full {
    max-height: 60vh;
    padding: 16px;
    overflow-y: auto;
    word-wrap: break-word; // Ensure long words break
    white-space: pre-wrap; // Preserve whitespace and newlines
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 4px;
  }
}

// Deep styling for el-dialog if necessary
:deep(.el-dialog__body) {
  padding: 15px 20px;
}
:deep(.el-dialog__footer) {
  padding: 10px 20px;
  border-top: 1px solid #f0f0f0;
}
:deep(.el-dialog__header) {
  padding: 15px 20px;
  margin-right: 0; // Reset element-plus default margin
  border-bottom: 1px solid #f0f0f0;
}
</style>
